package shop.core.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 二维码生成器工具类
 */
public class QRcodeUtils {

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 生成二维码
     * @param request
     * @param content 生成内容
     * @return  生成二维码路径
     */
    public static String createQrcode(HttpServletRequest request,String content){

        String rootPath=request.getSession().getServletContext().getRealPath("");
        String qrCodePath=rootPath+"/ueditor/upload/qrCodeImgs";
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyyMMddHHmmss" );
        Date nowDate=new Date();
        Random random = new Random();
        int s = random.nextInt(9999);
        String fileName=sdf.format(nowDate)+s+".png";
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map hints = new HashMap();
            //内容所使用编码
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            //生成二维码
            File outputFile = new File(qrCodePath,fileName);
            if(!outputFile.getParentFile().exists()){
                outputFile.getParentFile().mkdirs();
            }
            writeToFile(bitMatrix, "png", outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String FilePath="ueditor/upload/qrCodeImgs/"+fileName;
        return FilePath;
    }


    /**
     * 生成二维码
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 输出文件
     */
    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

}
